package com.mall.order.mq.delay;

import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.pay.PayCoreService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

@Component
public class DelayOrderCancelConsumer {

    @Autowired
    OrderMapper orderMapper;

    @Reference(check = false)
    PayCoreService payService;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;

    private DefaultMQPushConsumer consumer;

    @PostConstruct
    public void init() {
        // 创建用于消费消息的Consumer对象
        consumer = new DefaultMQPushConsumer("delay_order_cancel_consumer");

        // 2.设置nameserver地址
        consumer.setNamesrvAddr("127.0.0.1:9876");

        // 3. 设置消息监听器
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                // 1. 获取消息
                MessageExt message = msgs.get(0);
                String orderId = new String(message.getBody(), 0, message.getBody().length, StandardCharsets.UTF_8);
                // 2. 从消息中获取orderId
                // 3. 根据订单Id去数据库中，检查orderId对应的订单，有没有支付
                Order order = orderMapper.selectByPrimaryKey(orderId);
                // 如果已付款，那么order.status的值为1，
                boolean success = order.getStatus() == 1;
                //     a. 如果订单已经支付成功 或者订单已经被取消，啥也不干
                //     b. 如果订单处于初始化状态，指定时间内，没有支付成功，执行订单的取消
                if (!success) {
                    // 修改支付表中的订单状态
                    payService.changePaymentFailStatus(orderId);
                    // 修改订单状态为取消
                    orderMapper.cancleOrder(orderId);

                    // 更新item表中的状态
                    orderItemMapper.updateStockStatus(2, orderId);
                    List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
                    // 更新stock表中的库存
                    if (orderItems.size() != 0) {
                        for (OrderItem orderItem : orderItems) {
                            Stock stock = new Stock();
                            stock.setItemId(orderItem.getItemId());
                            int num = orderItem.getNum();
                            stock.setLockCount(-num);
                            stock.setStockCount((long) num);
                            stockMapper.updateStock(stock);
                        }
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });


        try {
            // 订阅主题
            consumer.subscribe("delay_order_cancel", "*");

            // 启动消费者
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }

}

